package com.hzx.zhihu.aop;

import com.hzx.zhihu.annotation.Log;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestAttribute;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;
import java.util.Date;

@Component
@Aspect// 表示切面类
public class SysAspect {

    @Pointcut("@annotation(com.hzx.zhihu.annotation.Log)")
    public void pointcut(){}

    @Around("pointcut()")
    public Object around(ProceedingJoinPoint joinPoint) throws Throwable{

        //获取被增强类和方法的信息
        Signature signature = joinPoint.getSignature();
        MethodSignature methodSignature = (MethodSignature) signature;

        //获取被增强的方法对象
        Method method = methodSignature.getMethod();

        //从方法中解析注解
        if(method!=null){
            Log log = method.getAnnotation(Log.class);
            System.out.println(log.name());
        }

        //方法名字
        String methodName = method.getName();
        System.out.println("方法名字："+methodName);

        //通过工具类获取Request对象
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
        ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) requestAttributes;
        HttpServletRequest request = servletRequestAttributes.getRequest();

        //访问的url
        String url = request.getRequestURL().toString();
        System.out.println("访问的url："+url);

        //访问的ip
        String ip = request.getRemoteAddr();
        System.out.println("访问的ip："+ip);

        //操作时间
        System.out.println(new Date());

        return joinPoint.proceed();
    }
}
